﻿using System.Runtime.InteropServices;
using Bzstd.Utility;
using Steamworks;

namespace Bzstd.Service;

public class CallResultHandle<T>
{
	private GCHandle _gcHandle;
	private CallResult<T> _callResult;
	private T result;
	public CallResultHandle(SteamAPICall_t call)
	{
		_callResult = CallResult<T>.Create(Callback);
		_callResult.Set(call);
		_gcHandle = GCHandle.Alloc(_callResult);
	}

	public void Callback(T t, bool b)
	{
		_gcHandle.Free();
		_callResult = null;
		result = t;
	}

	public async Task<T> GetResult()
	{
		await CommonUtility.WaitUntil(() => _callResult == null);
		return result ?? throw new Exception("失败");
	}

	public static T Call(SteamAPICall_t call)
	{
		return new CallResultHandle<T>(call).GetResult().Result;
	}
}
